<?php
/**
 * User: taodf
 * Date: 17-4-29
 * Time: 下午7:16
 */

namespace Zeus\View;

use Zeus\View\Engines\EngineFactory;
use Zeus\View\Engines\EngineInterface;

/**
 * 视图工厂类
 *
 * Class ViewFactory
 * @package Zeus\View
 */
class View
{
    /**
     * 视图引擎类型
     *
     * @var string $engineType
     */
    private $engineType;

    /**
     * 视图引擎
     *
     * @var EngineInterface $engine
     */
    private $engine;

    /**
     * 模板文件的目录
     *
     * @var string $folder
     */
    private $folder;

    public function __construct($folder, $type="plates")
    {
        $this->engineType=$type;
        $this->folder=$folder;
        $this->engine=EngineFactory::createEngine($type, $folder);
    }

    /**
     * 设置模板文件路径
     *
     * @param string $folder
     */
    public function setFolder($folder)
    {
        $this->folder=$folder;
    }

    /**
     * 设置视图引擎
     *
     * @param string $type
     * @param null|string $folder
     */
    public function setEngine($type, $folder=null)
    {
        $folder=is_null($folder)? $this->folder:$folder;
        $this->folder=$folder;
        $this->engine=EngineFactory::createEngine($type, $this->folder);
    }

    /**
     * 向视图中注入变量
     *
     * @param string $name
     * @param mixed $value
     * @return mixed
     */
    public function with($name, $value)
    {
        $this->engine->with($name, $value);
        return $this;
    }

    /**
     * 向视图中注入全局空间的变量
     *
     * @param string $name
     * @param mixed $value
     */
    public function share($name, $value)
    {
        $this->engine->share($name, $value);
    }

    /**
     * 渲染试图
     *
     * @param string $view
     * @param array $param
     * @return string
     */
    public function render($view, $param=[])
    {
        return $this->engine->render($view, $param);
    }

    /**
     * 为视图注入新的模板文件夹
     *
     * @param string $name
     * @param string $path
     */
    public function names($name, $path)
    {
        $this->engine->names($name, $path);
    }

    /**
     * 为视图注册新的功能
     *
     * @param string $func
     * @param callable $callable
     */
    public function feature($func, $callable)
    {
        $this->engine->feature($func, $callable);
    }

    /**
     * 渲染试图
     *
     * @return string
     */
    public function __toString()
    {
        return (string)$this->engine;
    }

}